package com.hmall.mq;

import com.alibaba.fastjson.JSON;
import com.hmall.client.ItemClient;
import com.hmall.pojo.Item;
import com.hmall.pojo.ItemDOC;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.action.delete.DeleteRequest;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.IOException;

/*
 *@author: RickChen
 *@description: 数据同步监听器
 *@Time: 2023/4/9  9:48
 */
@Component
@Slf4j
public class SearchListener {

    @Resource
    private RestHighLevelClient restHighLevelClient;

    @Resource
    ItemClient itemClient;

    /**
     * 更新ES数据（添加或修改时触发）
     *
     * @param id
     */
    @RabbitListener(bindings = @QueueBinding(
            value = @Queue("hmall.update.queue"),
            exchange = @Exchange(value = "hmall.topic", type = ExchangeTypes.TOPIC),
            key = "*.update"  // 所有以update结尾的都会被匹配
    ))
    public void updateListener(String id) {
        System.out.println("ES收到更新消息:" + id);

        try {
            Item item = itemClient.findById(Long.valueOf(id));
            ItemDOC itemDOC = new ItemDOC(item);

            IndexRequest indexRequest = new IndexRequest("hmall").id(id);
            indexRequest.source(JSON.toJSONString(itemDOC), XContentType.JSON);

            restHighLevelClient.index(indexRequest, RequestOptions.DEFAULT);
        } catch (IOException e) {
            e.printStackTrace();
            throw new RuntimeException("系统繁忙");
        }

    }


    /**
     * 删除ES数据
     *
     * @param id
     */
    @RabbitListener(bindings = @QueueBinding(
            value = @Queue("hmall.delete.queue"),
            exchange = @Exchange(value = "hmall.topic", type = ExchangeTypes.TOPIC),
            key = "*.delete"  // 所有以update结尾的都会被匹配
    ))
    public void deleteListener(String id) {
        System.out.println("ES收到删除消息:" + id);
        try {

            DeleteRequest deleteRequest = new DeleteRequest("hmall").id(id);

            restHighLevelClient.delete(deleteRequest, RequestOptions.DEFAULT);
        } catch (IOException e) {
            e.printStackTrace();
            throw new RuntimeException("系统繁忙");
        }

    }



}
